/**
 * 定义一个插件，用来自动将scatter/components/目录下的组件README.md注入到项目侧边栏
 * @type {module:fs}
 */
const fs = require('fs')
const path = require('path')
const components = 'components'
const readme = 'README.md'
module.exports = (options, ctx) => {
    return {
        async additionalPages ({ themeConfig}) {
            let componentsPath = path.resolve(__dirname, '../../../components')
            let files = fs.readdirSync(componentsPath)
            let r = []
            files.forEach(file=>{
                let filePath = componentsPath + '/' + file + '/' + readme
                if(fs.existsSync(componentsPath + '/' + file + '/' + readme)){
                    r.push({
                        path: '/' + components + '/' + file + '/',
                        filePath: filePath
                    })
                }
            })
            if(r.length > 0){
                themeConfig.sidebar.forEach(item=>{
                    if(Object.prototype.toString.call(item) === '[object Object]' && item.title == '组件'){
                        if(!item.children){
                            item.children = []
                        }
                        r.forEach(i => {
                            item.children.push(i.path)
                        })
                    }
                })
            }

            return r
        }
    }
}